package com.hongkuncheng.cms.controller.admin;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.sql.JoinType;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.helper.StringHelper;
import com.hongkuncheng.cms.model.Admin;
import com.hongkuncheng.cms.model.Form;
import com.hongkuncheng.cms.model.FormData;
import com.hongkuncheng.cms.model.FormDataAtisfaction;
import com.hongkuncheng.cms.model.FormField;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 表单数据管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/formdata")
public class AformdataController extends BaseController {

    // 表单数据列表
    @RequestMapping
    public String index() throws Exception {
        int formId = Integer.parseInt(request.getParameter("formid"));
        Form form = factorySession.get(Form.class, formId);
        request.setAttribute("form", form);
        List<FormField> formfields = factorySession.createCriteria(FormField.class)
                .add(Restrictions.eq("form.id", formId))
                .add(Restrictions.eq("listshow", true)).list();
        request.setAttribute("formfields", formfields);
        Criteria criteriaFormdatas = factorySession.createCriteria(FormData.class)
                .add(Restrictions.eq("form.id", formId));
        StringBuilder callbackparams = new StringBuilder();
        int state = request.getParameter("state") == null ? -1 : Integer.parseInt(request.getParameter("state"));
        if (state == 0) criteriaFormdatas.add(Restrictions.isNull("result"));
        else if (state == 1) criteriaFormdatas.add(Restrictions.isNotNull("result"));
        callbackparams.append("&state=" + state);
        request.setAttribute("state", state);
        String keywords = request.getParameter("keywords") == null ? "" : request.getParameter("keywords");
        if (!keywords.isEmpty()) {
            Disjunction disjunction = Restrictions.disjunction();
            for (int i = 1; i <= 100; i++)
                disjunction.add(Restrictions.like(
                        "field" + i, keywords, MatchMode.ANYWHERE));
            criteriaFormdatas.add(disjunction);
            callbackparams.append("&keywords=" + keywords);
        }
        request.setAttribute("keywords", keywords);
        if (callbackparams.length() > 0) callbackparams.deleteCharAt(0);
        request.setAttribute("callbackparams", callbackparams);
        int pageIndex = request.getParameter("pageindex") == null || request.getParameter("callbackparams") != null &&
                !callbackparams.toString().equals(request.getParameter("callbackparams")) ? 1 :
                Integer.parseInt(request.getParameter("pageindex"));
        int datasize = getDataSize();
        List<FormData> formdatas = criteriaFormdatas.addOrder(Order.desc("subtime"))
                .setFirstResult((pageIndex - 1) * datasize).setMaxResults(datasize).list();
        request.setAttribute("formdatas", formdatas);
        request.setAttribute("pageindex", pageIndex);
        int recordcount = formdatas.size() == 0 ? 0 :
                Integer.parseInt(criteriaFormdatas.setProjection(Projections.countDistinct("id"))
                        .setFirstResult(0).uniqueResult().toString());
        request.setAttribute("recordcount", recordcount);
        int pagecount = DataHelper.calcPageCount(recordcount, datasize);
        request.setAttribute("pagecount", pagecount);
        List<FormDataAtisfaction> atisfactions = factorySession.createCriteria(FormDataAtisfaction.class)
                .createAlias("formDatas", "formData", JoinType.LEFT_OUTER_JOIN)
                .createAlias("formData.form", "formData_form", JoinType.LEFT_OUTER_JOIN)
                .add(Restrictions.eq("formData_form.id", formId))
                .add(Restrictions.sizeGt("formDatas", 0))
                .list();
        request.setAttribute("atisfactions", atisfactions);
        return view();
    }

    // 表单数据详细
    @RequestMapping("detail")
    public String detail() throws Exception {
        int formdataId = Integer.parseInt(request.getParameter("formdataid"));
        FormData formdata = factorySession.get(FormData.class, formdataId);
        request.setAttribute("formdata", formdata);
        request.setAttribute("callbackparams", request.getParameter("callbackparams"));
        return view();
    }

    // 表单数据回复
    @RequestMapping("replay")
    @ResponseBody
    public void replay() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        int formdataId = Integer.parseInt(request.getParameter("formdataid"));
        FormData formdata = factorySession.get(FormData.class, formdataId, LockMode.PESSIMISTIC_WRITE);
        checkAdminPermission("office_form_" + formdata.getForm().getId());
        formdata.setDisposeUser(admin.getName());
        formdata.setResult(request.getParameter("result"));
        PageHelper.alertAndRedirect("回复成功", "./?formid=" + formdata.getForm().getId() + "&" +
                request.getParameter("callbackparams"));
    }

    // 表单数据删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        String[] formdataids = request.getParameter("formdataids").split(",");
        List<FormData> formdatas = factorySession.createCriteria(FormData.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(formdataids)))
                .setLockMode(LockMode.PESSIMISTIC_WRITE).list();
        for (FormData formdata : formdatas) checkAdminPermission("office_form_" + formdata.getForm().getId());
        for (FormData formdata : formdatas) factorySession.delete(formdata);
        PageHelper.alertAndRedirect("删除成功", "./?formid=" + formdatas.get(0).getForm().getId() + "&" +
                request.getParameter("callbackparams"));
    }

}
